<template>
  <div class="columns py-6">
    <div class="column is-half is-offset-one-quarter">
      <el-card shadow="never">
        <div slot="header" class="has-text-centered has-text-weight-bold">
          用户登录
        </div>
        <div>
          <el-form
            ref="ruleForm"
            v-loading="loading"
            :model="ruleForm"
            :rules="rules"
            class="demo-ruleForm"
            label-width="100px"
            status-icon
          >
            <el-form-item label="账号" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="pass">
              <el-input
                v-model="ruleForm.pass"
                autocomplete="off"
                type="password"
              ></el-input>
            </el-form-item>

            <el-form-item label="记住" prop="delivery">
              <el-switch v-model="ruleForm.rememberMe"></el-switch>
              <el-link
                :underline="false"
                class="resetpassword ml-6"
                type="warning"
                @click="openResetPasswordModal"
              >
                忘记密码
              </el-link>
              <el-dialog :visible.sync="visible" title="重置密码">
                <el-form ref="form" :model="form" :rules="rules">
                  <el-form-item label="用户名" prop="username">
                    <el-input
                      v-model="form.username"
                      placeholder="请输入用户名"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" prop="password">
                    <el-input
                      v-model="form.password"
                      placeholder="请输入新密码"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="验证码" prop="captcha">
                    <el-input v-model="form.captcha" />
                    <img
                      :src="captcha.img"
                      @click="getCaptcha()"
                      class="ml-4 captcha-img"
                    />
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="visible = false">取消</el-button>
                  <el-button type="primary" @click="resetPassword"
                    >重置密码</el-button
                  >
                </div>
              </el-dialog>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >提交</el-button
              >
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import axios from "axios";

axios.defaults.baseURL = "http://localhost:8000"; // 后端接口地址

export default {
  name: "Login",
  data() {
    return {
      visible: false,
      redirect: undefined,
      captcha: {
        code: "", // 验证码字符串
        img: "", // 验证码图片Base64
      },
      loading: false,
      showResetPasswordModal: false,
      form: {
        username: "",
        password: "",
      },
      ruleForm: {
        name: "",
        pass: "",
        rememberMe: true,
      },
      rules: {
        name: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        pass: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.ruleForm)
            .then(() => {
              this.$message({
                message: "恭喜你，登录成功",
                type: "success",
                duration: 2000,
              });

              setTimeout(() => {
                this.loading = false;
                console.log(this.ruleForm.name);
                if (this.ruleForm.name == "admin") {
                  this.$router.push({ path: "/admin" });
                } else {
                  this.$router.push({ path: this.redirect || "/" });
                }
              }, 0.1 * 1000);
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    openResetPasswordModal() {
      this.visible = true;
      this.getCaptcha();
    },
    getCaptcha() {
      // axios.get("/captcha/getCode").then((res) => {
      //   console.log(res);
      //   this.captcha.code = res.data.message;
      // })
        axios.get("/captcha/getVerifyCode").then((res) => {
          console.log(res);
          this.captcha.img = res.data.data.img;
          if (/^data:image\/\w+;base64,[\w+/=]+$/.test(this.captcha.img)) {
            this.captcha.code = res.data.data.code
          } else {
            this.$message.error("验证码格式错误!");
          }
        });
    },
    resetPassword() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.captcha.toLowerCase() !== this.captcha.code.toLowerCase()) {
            return this.$message.error("验证码错误!");
          }
          axios
            .post("/ums/user/resetPassword", this.form)
            .then(() => {
              this.$message.success("重置密码成功，请用新密码登录！");
              this.visible = false;
            })
            .catch(() => {
              this.$message.error("重置密码失败，请检查用户名是否正确！");
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped></style>